package com.ahearttogo.rpc.server;

import com.ahearttogo.rpc.common.utils.ReflectionUtil;
import com.ahearttogo.rpc.proto.Request;
import com.ahearttogo.rpc.proto.ServiceDescriptor;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 管理rpc暴露的服务
 * @author xiejialin
 * @date 2020/2/17 3:44 PM
 */
@Slf4j
public class ServiceManager {

    private Map<ServiceDescriptor,ServiceInstance> services;

    public ServiceManager(){
        this.services = new ConcurrentHashMap<>();
    }

    /**
     *
     * @param interfaceClass 接口的class
     * @param bean 接口具体实现类的一个对象
     */
    public <T> void register(Class<T> interfaceClass,T bean){
        Method[] methods = ReflectionUtil.getPublicMethods(interfaceClass);
        for(Method method : methods) {
            ServiceInstance sis = new ServiceInstance(bean,method);
            ServiceDescriptor sdp = ServiceDescriptor.from(interfaceClass,method);
            services.put(sdp,sis);
            log.info("register service: {} {}", sdp.getClazz(),sdp.getMethod());
        }
    }

    /**
     * 查找服务
     * @param request
     * @return
     */
    public ServiceInstance search(Request request) {
        ServiceDescriptor sdp = request.getService();
        return services.get(sdp);
    }
}
